package com.jy.users.service.impl;

import java.util.List;

import com.jy.records.domain.BorrowRecords;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import com.jy.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.jy.users.mapper.UsersMapper;
import com.jy.users.domain.Users;
import com.jy.users.service.IUsersService;

/**
 * 用户信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-05-29
 */
@Service
public class UsersServiceImpl implements IUsersService 
{
    @Autowired
    private UsersMapper usersMapper;

    /**
     * 查询用户信息
     * 
     * @param userId 用户信息主键
     * @return 用户信息
     */
    @Override
    public Users selectUsersByUserId(Long userId)
    {
        return usersMapper.selectUsersByUserId(userId);
    }

    /**
     * 查询用户信息列表
     * 
     * @param users 用户信息
     * @return 用户信息
     */
    @Override
    public List<Users> selectUsersList(Users users)
    {
        return usersMapper.selectUsersList(users);
    }

    /**
     * 新增用户信息
     * 
     * @param users 用户信息
     * @return 结果
     */
    @Transactional
    @Override
    public int insertUsers(Users users)
    {
        int rows = usersMapper.insertUsers(users);
        insertBorrowRecords(users);
        return rows;
    }

    /**
     * 修改用户信息
     * 
     * @param users 用户信息
     * @return 结果
     */
    @Transactional
    @Override
    public int updateUsers(Users users)
    {
        usersMapper.deleteBorrowRecordsByUserId(users.getUserId());
        insertBorrowRecords(users);
        return usersMapper.updateUsers(users);
    }

    /**
     * 批量删除用户信息
     * 
     * @param userIds 需要删除的用户信息主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteUsersByUserIds(Long[] userIds)
    {
        usersMapper.deleteBorrowRecordsByUserIds(userIds);
        return usersMapper.deleteUsersByUserIds(userIds);
    }

    /**
     * 删除用户信息信息
     * 
     * @param userId 用户信息主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteUsersByUserId(Long userId)
    {
        usersMapper.deleteBorrowRecordsByUserId(userId);
        return usersMapper.deleteUsersByUserId(userId);
    }

    /**
     * 新增借阅记录信息
     * 
     * @param users 用户信息对象
     */
    public void insertBorrowRecords(Users users)
    {
        List<BorrowRecords> borrowRecordsList = users.getBorrowRecordsList();
        Long userId = users.getUserId();
        if (StringUtils.isNotNull(borrowRecordsList))
        {
            List<BorrowRecords> list = new ArrayList<BorrowRecords>();
            for (BorrowRecords borrowRecords : borrowRecordsList)
            {
                borrowRecords.setUserId(userId);
                list.add(borrowRecords);
            }
            if (list.size() > 0)
            {
                usersMapper.batchBorrowRecords(list);
            }
        }
    }
}
